package com.xinghanlaser.applet.base.common.utils;

import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.xinghanlaser.applet.base.common.entity.ResponseEntity;
import com.xinghanlaser.applet.base.common.vo.PageVO;


import java.util.List;
import java.util.Optional;
import java.util.function.Function;
import java.util.function.Supplier;

/**
 * <p>
 *  封装分页查询工具，使用PageHelper插件
 * <p>
 *
 * @author: mftuo
 * @since: 2024/2/28 14:47
 */
public class QueryUtil {
    public static <E> ResponseEntity.PageResult<E> query(PageVO pageVO,
                                                         Supplier<List<E>> supplier){
        return query(pageVO, supplier, x->x);
    }

    public static <E,R> ResponseEntity.PageResult<R> query(PageVO pageVO,
                                                         Supplier<List<E>> supplier,
                                                         Function<List<E>, List<R>> function){
        ResponseEntity.PageResult<R> result = new ResponseEntity.PageResult<>();

        //获取分页记录DO
        List<E> records = Optional.ofNullable(pageVO)
                .filter(query -> ObjectUtil.isAllNotEmpty(query.getPage(), query.getSize()))
                .map(query -> {
                    Page<E> page = PageHelper.startPage(
                            pageVO.getPage(),
                            pageVO.getSize()
                    ).doSelectPage(supplier::get);

                    //写入分页相关参数
                    List<E> listResult = page.getResult();
                    result.setTotal(listResult.isEmpty() ? 0 : page.getTotal());

                    return listResult;
                })
                .orElseGet(supplier);

        //转化为VO
        Optional.ofNullable(function)
                .ifPresent(x -> result.setRecords(x.apply(records)));

        return result;
    }
}
